<template>
  <div class="story-generator">
    <div class="container">
      <div class="generator-header">
        <h1 class="page-title">AI故事生成器</h1>
        <p class="page-description">
          输入你的创意想法，让AI为你创造独特的故事
        </p>
      </div>

      <div class="generator-content">
        <div class="generator-form">
          <div class="form-section">
            <div class="form-group">
              <label class="form-label">故事主题或关键词</label>
              <input
                v-model="storyPrompt"
                type="text"
                class="form-input"
                placeholder="例如：勇敢的公主、神秘的森林、时间旅行..."
                @keyup.enter="generateStory"
              />
            </div>

            <div class="form-group">
              <label class="form-label">故事类型</label>
              <select v-model="selectedCategory" class="form-select">
                <option 
                  v-for="category in storiesStore.categories" 
                  :key="category"
                  :value="category"
                >
                  {{ category }}
                </option>
              </select>
            </div>

            <div class="form-group">
              <label class="form-label">故事长度</label>
              <div class="length-options">
                <label 
                  v-for="option in lengthOptions" 
                  :key="option.value"
                  class="length-option"
                >
                  <input
                    v-model="selectedLength"
                    type="radio"
                    :value="option.value"
                    class="length-radio"
                  />
                  <span class="length-label">{{ option.label }}</span>
                  <span class="length-desc">{{ option.description }}</span>
                </label>
              </div>
            </div>

            <div class="form-actions">
              <button
                @click="generateStory"
                :disabled="!storyPrompt.trim() || storiesStore.isGenerating"
                class="btn btn-primary btn-lg generate-btn"
              >
                <div v-if="storiesStore.isGenerating" class="loading">
                  <div class="spinner"></div>
                  <span>AI正在创作中...</span>
                </div>
                <div v-else class="btn-content">
                  <Sparkles :size="20" />
                  <span>生成故事</span>
                </div>
              </button>
            </div>
          </div>
        </div>

        <div class="generator-preview">
          <div v-if="!currentStory && !storiesStore.isGenerating" class="preview-placeholder">
            <div class="placeholder-icon">
              <BookOpen :size="64" />
            </div>
            <h3>你的故事将在这里显示</h3>
            <p>输入创意提示，点击生成按钮开始创作</p>
          </div>

          <div v-else-if="storiesStore.isGenerating" class="generating-animation">
            <div class="typing-animation">
              <div class="typing-dots">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
            <h3>AI正在为你创作故事...</h3>
            <p>请稍候，创意正在生成中</p>
          </div>

          <div v-else-if="currentStory" class="story-preview">
            <div class="story-header">
              <h2>{{ currentStory.title }}</h2>
              <span class="story-category">{{ currentStory.category }}</span>
            </div>
            
            <div class="story-content">
              <div 
                ref="storyText"
                class="story-text"
                v-html="formatStoryContent(currentStory.content)"
              ></div>
            </div>

            <div class="story-actions">
              <button @click="publishStory" class="btn btn-primary">
                <Send :size="16" />
                发布故事
              </button>
              <button @click="editStory" class="btn btn-secondary">
                <Edit :size="16" />
                编辑故事
              </button>
              <button @click="regenerateStory" class="btn btn-ghost">
                <RefreshCw :size="16" />
                重新生成
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- Story Editor Modal -->
      <div v-if="showEditor" class="editor-modal">
        <div class="editor-content">
          <div class="editor-header">
            <h3>编辑故事</h3>
            <button @click="closeEditor" class="close-btn">
              <X :size="20" />
            </button>
          </div>
          
          <div class="editor-form">
            <div class="form-group">
              <label class="form-label">故事标题</label>
              <input
                v-model="editingStory.title"
                type="text"
                class="form-input"
              />
            </div>
            
            <div class="form-group">
              <label class="form-label">故事内容</label>
              <textarea
                v-model="editingStory.content"
                class="form-textarea story-editor"
                rows="15"
              ></textarea>
            </div>
            
            <div class="editor-actions">
              <button @click="saveEditedStory" class="btn btn-primary">
                <Save :size="16" />
                保存修改
              </button>
              <button @click="publishEditedStory" class="btn btn-success">
                <Send :size="16" />
                保存并发布
              </button>
              <button @click="closeEditor" class="btn btn-secondary">
                取消
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useStoriesStore } from '../stores/stories'
import { useAuthStore } from '../stores/auth'
import { useToast } from 'vue-toastification'
import { gsap } from 'gsap'
import { 
  Sparkles, 
  BookOpen, 
  Save, 
  Edit, 
  RefreshCw, 
  X,
  Send
} from 'lucide-vue-next'

const router = useRouter()
const storiesStore = useStoriesStore()
const authStore = useAuthStore()
const toast = useToast()

const storyPrompt = ref('')
const selectedCategory = ref('奇幻')
const selectedLength = ref('medium')
const showEditor = ref(false)
const storyText = ref(null)
const currentStory = ref(null)

const editingStory = reactive({
  title: '',
  content: ''
})

const lengthOptions = ref([
  {
    value: 'short',
    label: '短篇',
    description: '200-500字'
  },
  {
    value: 'medium',
    label: '中篇',
    description: '500-1000字'
  },
  {
    value: 'long',
    label: '长篇',
    description: '1000字以上'
  }
])

const generateStory = async () => {
  // 检查用户是否已登录
  if (!authStore.isAuthenticated) {
    toast.error('请先登录后再创作故事')
    return
  }

  if (!storyPrompt.value.trim()) {
    toast.error('请输入故事主题或关键词')
    return
  }

  try {
    // 根据选择的长度确定字数
    const getWordCount = () => {
      switch (selectedLength.value) {
        case 'short': return 200
        case 'medium': return 500
        case 'long': return 1000
        default: return 500
      }
    }

    const result = await storiesStore.generateStory(
      storyPrompt.value,
      selectedCategory.value,
      getWordCount()
    )

    if (result.success) {
      currentStory.value = result.story
      toast.success('故事生成成功！您可以编辑后发布。')
      
      // 添加打字机动画效果
      nextTick(() => {
        if (storyText.value) {
          gsap.fromTo(storyText.value.children,
            { opacity: 0, y: 20 },
            {
              opacity: 1,
              y: 0, 
              duration: 0.8, 
              stagger: 0.1,
              ease: 'power2.out'
            }
          )
        }
      })
    }
  } catch (error) {
    console.error('故事生成失败:', error)
    toast.error('故事生成失败，请检查网络连接后重试')
  }
}

const publishStory = async () => {
  if (currentStory.value) {
    try {
      await storiesStore.publishStory(currentStory.value.id)
      toast.success('故事发布成功！')
      setTimeout(() => {
        router.push('/library')
      }, 1500)
    } catch (error) {
      toast.error('发布失败：' + (error.message || '请重试'))
    }
  }
}

const editStory = () => {
  if (currentStory.value) {
    editingStory.title = currentStory.value.title
    editingStory.content = currentStory.value.content
    showEditor.value = true
  }
}

const closeEditor = () => {
  showEditor.value = false
}

const saveEditedStory = async () => {
  if (currentStory.value) {
    try {
      currentStory.value.title = editingStory.title
      currentStory.value.content = editingStory.content
      await storiesStore.saveStory(currentStory.value)
      closeEditor()
      toast.success('故事修改已保存')
    } catch (error) {
      toast.error('保存失败：' + (error.message || '请重试'))
    }
  }
}

const publishEditedStory = async () => {
  if (currentStory.value) {
    try {
      currentStory.value.title = editingStory.title
      currentStory.value.content = editingStory.content
      await storiesStore.saveStory(currentStory.value)
      await storiesStore.publishStory(currentStory.value.id)
      closeEditor()
      toast.success('故事发布成功！')
      setTimeout(() => {
        router.push('/library')
      }, 1500)
    } catch (error) {
      toast.error('发布失败：' + (error.message || '请重试'))
    }
  }
}

const regenerateStory = () => {
  generateStory()
}

const formatStoryContent = (content) => {
  return content.replace(/\n/g, '<br>')
}

onMounted(() => {
  // Animate form elements
  gsap.fromTo('.form-section > *',
    { opacity: 0, x: -30 },
    { 
      opacity: 1, 
      x: 0, 
      duration: 0.6, 
      stagger: 0.1,
      ease: 'power2.out'
    }
  )
  
  gsap.fromTo('.preview-placeholder',
    { opacity: 0, scale: 0.9 },
    { 
      opacity: 1, 
      scale: 1, 
      duration: 0.8,
      ease: 'back.out(1.7)'
    }
  )
})
</script>

<style scoped>
.story-generator {
  padding: var(--spacing-2xl) 0;
  min-height: 100vh;
}

.generator-header {
  text-align: center;
  margin-bottom: var(--spacing-3xl);
}

.page-title {
  font-size: var(--font-size-3xl);
  margin-bottom: var(--spacing-md);
  background: var(--gradient-primary);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.page-description {
  font-size: var(--font-size-lg);
  color: var(--text-secondary);
  max-width: 600px;
  margin: 0 auto;
}

.generator-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: var(--spacing-3xl);
  align-items: start;
}

.generator-form {
  background: var(--bg-secondary);
  border-radius: var(--radius-xl);
  padding: var(--spacing-2xl);
  border: 1px solid var(--border-color);
  box-shadow: var(--shadow-lg);
}

.form-section > .form-group:not(:last-child) {
  margin-bottom: var(--spacing-xl);
}

.length-options {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-md);
}

.length-option {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
  padding: var(--spacing-md);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-md);
  cursor: pointer;
  transition: all var(--transition-fast);
}

.length-option:hover {
  border-color: var(--primary-color);
  background: rgba(102, 126, 234, 0.05);
}

.length-radio {
  margin: 0;
}

.length-label {
  font-weight: 500;
  color: var(--text-primary);
  min-width: 60px;
}

.length-desc {
  color: var(--text-secondary);
  font-size: var(--font-size-sm);
}

.generate-btn {
  width: 100%;
  position: relative;
  overflow: hidden;
}

.generate-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.btn-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--spacing-sm);
}

.generator-preview {
  background: var(--bg-secondary);
  border-radius: var(--radius-xl);
  padding: var(--spacing-2xl);
  border: 1px solid var(--border-color);
  box-shadow: var(--shadow-lg);
  min-height: 600px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.preview-placeholder {
  text-align: center;
  color: var(--text-secondary);
}

.placeholder-icon {
  margin-bottom: var(--spacing-lg);
  color: var(--text-muted);
}

.generating-animation {
  text-align: center;
  color: var(--text-secondary);
}

.typing-animation {
  margin-bottom: var(--spacing-xl);
}

.typing-dots {
  display: flex;
  justify-content: center;
  gap: var(--spacing-sm);
}

.typing-dots span {
  width: 12px;
  height: 12px;
  background: var(--primary-color);
  border-radius: 50%;
  animation: typing 1.4s ease-in-out infinite;
}

.typing-dots span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-dots span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
    opacity: 0.4;
  }
  30% {
    transform: translateY(-20px);
    opacity: 1;
  }
}

.story-preview {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.story-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: var(--spacing-xl);
  padding-bottom: var(--spacing-lg);
  border-bottom: 1px solid var(--border-color);
}

.story-header h2 {
  flex: 1;
  margin: 0;
  color: var(--text-primary);
}

.story-category {
  background: var(--gradient-primary);
  color: white;
  padding: var(--spacing-xs) var(--spacing-sm);
  border-radius: var(--radius-sm);
  font-size: var(--font-size-xs);
  font-weight: 500;
}

.story-content {
  flex: 1;
  margin-bottom: var(--spacing-xl);
}

.story-text {
  color: var(--text-secondary);
  line-height: 1.8;
  font-size: var(--font-size-base);
}

.story-actions {
  display: flex;
  gap: var(--spacing-md);
  flex-wrap: wrap;
}

/* Editor Modal */
.editor-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: var(--spacing-lg);
}

.editor-content {
  background: var(--bg-secondary);
  border-radius: var(--radius-xl);
  width: 100%;
  max-width: 800px;
  max-height: 90vh;
  overflow-y: auto;
  border: 1px solid var(--border-color);
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--spacing-xl);
  border-bottom: 1px solid var(--border-color);
}

.editor-header h3 {
  margin: 0;
  color: var(--text-primary);
}

.close-btn {
  background: transparent;
  border: none;
  color: var(--text-secondary);
  cursor: pointer;
  padding: var(--spacing-sm);
  border-radius: var(--radius-md);
  transition: all var(--transition-fast);
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.05);
  color: var(--text-primary);
}

.editor-form {
  padding: var(--spacing-xl);
}

.story-editor {
  min-height: 300px;
  font-family: 'Courier New', monospace;
  line-height: 1.6;
}

.editor-actions {
  display: flex;
  gap: var(--spacing-md);
  justify-content: flex-end;
  margin-top: var(--spacing-xl);
}

/* Mobile Styles */
@media (max-width: 768px) {
  .generator-content {
    grid-template-columns: 1fr;
    gap: var(--spacing-2xl);
  }

  .generator-form,
  .generator-preview {
    padding: var(--spacing-lg);
  }

  .story-actions {
    flex-direction: column;
  }

  .story-actions .btn {
    width: 100%;
  }

  .editor-modal {
    padding: var(--spacing-sm);
  }

  .editor-content {
    max-height: 95vh;
  }

  .editor-header,
  .editor-form {
    padding: var(--spacing-lg);
  }
}
</style>
